<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="GAMS教程 3：子集与条件表达式, python,machine learning,deep learning,html,css,c,c++,cpp,cmake,ros,linux,ubuntu">
    <meta name="description" content="本文介绍了GAMS中的子集与条件表达式">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>GAMS教程 3：子集与条件表达式 | JackWang&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 5.4.2">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size: 100% 100%;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">JackWang&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-book-reader" style="zoom: 0.6;"></i>
      
      <span>博客</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按标签归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按目录归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按日期分类文章</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>



<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">JackWang&#39;s Blog</div>
        <div class="logo-desc">
            
            JackWang的个人博客
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book-reader"></i>
			
			博客
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
                              <span>按标签归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
                              <span>按目录归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
                              <span>按日期分类文章</    span>

                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('抱歉，这篇文章并不想让所有人都看到，请输入授权密码观看')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221016023519058.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">GAMS教程 3：子集与条件表达式</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/GAMS/">
                                <span class="chip bg-color">GAMS</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/GAMS/" class="post-category">
                                GAMS
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-10-15
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-06-01
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.2k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    12 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221016023519058.png" alt="GAMS文档：条件表达式"></p>
<h1 id="GAMS教程-3：子集与条件表达式"><a href="#GAMS教程-3：子集与条件表达式" class="headerlink" title="GAMS教程 3：子集与条件表达式"></a>GAMS教程 3：子集与条件表达式</h1><p>我们在前面的章节中介绍了GAMS中的基础数据类型、GAMS程序的基本结构、GAMS语法、GAMS的基本运算符以及GAMS中的函数。</p>
<p>本节我们将继续深入，讲解GAMS中的子集与逻辑表达式。</p>
<h2 id="1-子集-Subset-Dynamic-Set"><a href="#1-子集-Subset-Dynamic-Set" class="headerlink" title="1. 子集(Subset/Dynamic Set)"></a>1. 子集(Subset/Dynamic Set)</h2><p>我们在最前面介绍了GAMS中的基础数据类型：集合（Set）、参数（Parameter）、表格（Table）、标量（Scalar）以及变量（Variable）</p>
<p>其中：</p>
<ul>
<li>变量可以是集合、参数、表格、标量中的任意一种。</li>
<li>集合和参数、表格不同。集合起着索引的作用，而没有具体的值；参数和表格和具体得集合关联，并且对应集合中每一个元素都有对应的值。</li>
</ul>
<p><strong>本节中我们将介绍集合的另外一个知识，即子集</strong>。</p>
<p><strong>GAMS中将数学上的子集（Subset）称为动态集合（Dynamic Set），而之所以将子集称为动态集合，是因为GAMS中允许向子集中随时增减元素</strong>。相反，<strong>前面的介绍的集合中的元素是不能动态增减的，因此相应的称为静态集合（Static Set）</strong></p>
<h3 id="A-子集的声明"><a href="#A-子集的声明" class="headerlink" title="A. 子集的声明"></a>A. 子集的声明</h3><p><code>GAMS</code>中子集声明的语法如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set dynamic_set_name(parent_set_name)    [/item1, {item2}/];
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其中：</p>
<ul>
<li><code>[]</code>表示可选项，<code>{}</code>表示可重复项</li>
<li><code>parent_set_name</code>表示子集的父集。<strong>需要注意的是，在声明子集的时候，一定要先声明父集</strong>。</li>
<li><strong>如果在声明子集的时候指定子集中包含的元素，那么子集中的元素必须包含在父集中。因为GAMS会进行范围检查（Domain Check），如果子集中存在不在父集中的元素的话，那么就会报错。</strong></li>
</ul>
<p>下面给出一个声明子集的例子。</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set  item            "all items"              / dish, ink, lipstick, pen, pencil, perfume /,
     subitem1(item)  "first subset of item"   / pen, pencil /,
     subitem2(item)  "second subset of item";
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>需要注意的是，子集的声明和参数很类似，都是<code>变量名字(另一个集合名字)</code>的形式。</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set set_a /one, two, three, four/;

; 子集的()表示声明父集
Set subset(set_a) /one, four/;

; 参数的()是和索引集合关联
Parameter param(set_a) /"one" 1, "two" 2/;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>虽然形式一样，但其实两者存在本质上的不同。<code>GAMS</code>编译器会根据上下文来区别对待。</p>
<h3 id="B-子集动态元素增减"><a href="#B-子集动态元素增减" class="headerlink" title="B. 子集动态元素增减"></a>B. 子集动态元素增减</h3><p>我们前面说过，之所以<code>GAMS</code>中将子集称为动态集合，就是因为GAMS中的子集可以动态增减元素。</p>
<p><code>GAMS</code>中子集动态增减元素的语法如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">set_name(index_list | label) = yes | no ;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其中：</p>
<ul>
<li><code>yes</code>/<code>no</code>分别表示将元素加入集合或者从集合中删除</li>
<li><code>index_list</code>表示对某个集合整体设置，而<code>label</code>表示对某个元素进行设置</li>
</ul>
<p>子集的动态增减如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set  item            "all items"              / dish, ink, lipstick, pen, pencil, perfume /
     subitem1(item)  "first subset of item"   / pen, pencil /
     subitem2(item)  "second subset of item";

* subitem1 = /pen, pencil/;
* subitem2 = null;


subitem1('ink')      = yes;   * subitem1 = /pen, pencil, ink/;
subitem1('lipstick') = yes;   * subitem1 = /pen, pencil, ink, lipstick/;
subitem2(item)       = yes;   * subitem2 = /disk, ink, lipstick, pen, pencil, perfume/;
subitem2('perfume')  = no ;   * subitem2 = /disk, ink, lipstick, pen, pencil/;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>index_list</code>可以是一个静态集合，也可以是一个动态集合，即子集。</p>
<h2 id="2-条件表达式"><a href="#2-条件表达式" class="headerlink" title="2. 条件表达式"></a>2. 条件表达式</h2><p><code>GAMS</code>中提供了条件表达式，我们下面就将介绍进行介绍。</p>
<h3 id="1-条件表达式的声明"><a href="#1-条件表达式的声明" class="headerlink" title="1. 条件表达式的声明"></a>1. 条件表达式的声明</h3><p><code>GAMS</code>中条件表达式的语法如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">term $ logical_condition
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>即</p>
<pre class="line-numbers language-gas"><code class="language-gas">项 $ 逻辑表达式
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>条件表达式类似于C语言中的三元运算符，但是相比于三元运算符能够根据逻辑表达语句的值在两个项中选择，<strong><code>GAMS</code>中的条件表达式只能根据逻辑表达式的值在有项和无项之间选择</strong>。</p>
<p>例如下面这段C语言代码</p>
<pre class="line-numbers language-c"><code class="language-c"><span class="token keyword">if</span> <span class="token punctuation">(</span>b <span class="token operator">></span> <span class="token number">1.5</span><span class="token punctuation">)</span>
  a <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
<span class="token keyword">else</span>
    a <span class="token operator">=</span> null<span class="token punctuation">;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>注意，这里的<code>null</code>并不是C语言中的<code>null</code>，而是直接没有这项。上面的C语言的描述使用<code>GAMS</code>的条件表达式描述，如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">a $ (b > 1.5) = 2 ;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>再举例来说</p>
<pre class="line-numbers language-gas"><code class="language-gas">Scalar x /15/;
Scalar y;

y = 12$(x < 20);
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>表示如果<code>x</code>的值小于<code>20</code>，那么<code>y=12</code>，否则<code>y</code>的值就依旧是待定的。</p>
<p>再举一个例子，如果我们想要实现下面这段C语言程序</p>
<pre class="line-numbers language-c"><code class="language-c"><span class="token keyword">if</span> <span class="token punctuation">(</span>x <span class="token operator">&lt;</span> <span class="token number">20</span><span class="token punctuation">)</span>
      y <span class="token operator">=</span> <span class="token number">12</span><span class="token punctuation">;</span>
<span class="token keyword">else</span>
      y <span class="token operator">=</span> <span class="token number">21</span><span class="token punctuation">;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>对应的<code>GAMS</code>的语句为</p>
<pre class="line-numbers language-gas"><code class="language-gas">Scalar x /15/;
Scalar y;

y = 12$(x < 20) + 21$(x >= 20);
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>注意<code>GAMS</code>中的条件语句在条件不成立的时候直接就没有这一项，所以不要看这里有两个条件语句，<code>y = 12$(x &lt; 20) + 21$(x &gt;= 20)</code>这个表达式，其实在任何时候都只有一项。当然这个其实还和我们的条件有关。</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set A /1, 2, 3, 4, 5, 6/;
Parameter param(A);

param(A) = 1$(ord(A) < 4);
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="2-条件表达式与参数"><a href="#2-条件表达式与参数" class="headerlink" title="2. 条件表达式与参数"></a>2. 条件表达式与参数</h3><p>我们上面的例子中展示了如何使用条件表达式为一个标量赋值，条件表达式其实也能够为参数赋值</p>
<h4 id="子集"><a href="#子集" class="headerlink" title="子集"></a>子集</h4><p>对于逻辑表达式与子集的结合，我们举例如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set        i     / i1*i5 /
           j(i)  / i1*i3 / ;
Parameter  s(i)  / i1 3, i2 5, i3 11, i4 8, i5 1 /
           t(i);

t(i) $ j(i) = s(i) + 3;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>首先，集合<code>j</code>是集合<code>i</code>的子集，而<strong>逻辑表达式<code>t(i)$j(i)</code>则表示对于集合<code>j(i)</code>中的所有值</strong>。</p>
<p>因此参数<code>t(i)</code>最终的值为</p>
<pre class="line-numbers language-gas"><code class="language-gas">t(i) = / "i1" 6, "i2" 8, "i3" 14/;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h4 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h4><p>对于逻辑表达式与参数的使用，我们举例如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set        i     / i1*i5 /
Parameter  s(i)  / i1 3, i2 5, i3 11, i4 8, i5 1 /
           t(i);

t(i) $ (s(i) < 6) = s(i) + 3;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>首先，<code>s(i)</code>与<code>t(i)</code>都是参数，而逻辑表达式<code>t(i) $ (s(i) &lt; 6)</code>表示遍历<code>s</code>中的所有元素。当<code>s(i)</code>的值小于6时，存在<code>t(i)</code>这一项，否则就不存在。</p>
<p>所以<code>t(i)</code>最终的值为</p>
<pre class="line-numbers language-gas"><code class="language-gas">t(i) = /"i1" 6, "i2" 8, "i5" 4/
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h4 id="ord函数"><a href="#ord函数" class="headerlink" title="ord函数"></a>ord函数</h4><p>逻辑表达式与<code>ord</code>函数的联合使用如下</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set I /a, b, c, d, e, f/;
Parameter X(I) /"a" -1, "b" -2, "c" -3, "d" -4, "e" -5, "f" -6/;
Parameter A(I);

A(I) = 1$(ord(I) <= 2) + X(I-2)$(ord(I) > 2);
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>ord</code>函数将会返回一个参数，具体来说，该参数的值为<code>/"a" 1, "b" 2, "c" 3, "d" 4, "e" 5, "f" 6/</code></p>
<p>那么这个时候，情况就转为了上面逻辑表达式与参数的情况。此外，还需要注意的是<code>X(I-2)</code>这一项。<code>GAMS</code>中对参数取值的时候，对<code>index</code>集合进行减法，则只有当括号里的值大于0的时候，才会获取参数的内容。</p>
<p>所以对于<code>X(I-2)</code>这一项，当<code>I &gt; 2</code>的时候，才会取参数<code>X</code>中的值。</p>
<p>所以综上，表达式<code>A(I) = 1$(ord(I) &lt;= 2) + X(I-2)$(ord(I) &gt; 2)</code>的意思就是，让<code>A(I)</code>的前两项是1，后面的项等于<code>X</code>的前面的项。</p>
<p>所以<code>A(I)</code>最终的值为：</p>
<pre class="line-numbers language-gas"><code class="language-gas">A(I) = /"a" 1, "b" 1, "c" -1, "d" -2, "e" -3, "f" -4/;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h3 id="3-逻辑表达式与逻辑运算符"><a href="#3-逻辑表达式与逻辑运算符" class="headerlink" title="3. 逻辑表达式与逻辑运算符"></a>3. 逻辑表达式与逻辑运算符</h3><p>上面我们说<code>GAMS</code>中的条件表达式是根据逻辑表达式的值来计算项的，但是我们其实并没有详细的介绍<code>GAMS</code>中的逻辑表达式。</p>
<p>我们下面就将详细讲解<code>GAMS</code>中的逻辑表达式，以及与此相关的逻辑运算符。</p>
<h4 id="逻辑表达式"><a href="#逻辑表达式" class="headerlink" title="逻辑表达式"></a>逻辑表达式</h4><p><code>GAMS</code>中的逻辑表达式的值判断准则很简单，<strong>计算得到的逻辑表达式的值为0则为False，除此以外所有值都为True</strong></p>
<p>例如下面的例子</p>
<pre class="line-numbers language-gas"><code class="language-gas">b $ (2*a - 4) = 7;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>当<code>a = 2</code>时，逻辑表达式<code>2*a - 4</code>的逻辑值为False，其他时候都是True。</p>
<p>注意，集合没有值，而参数有值，所有以后有些情况我们可以这样写</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set i /a * e/,
        j(i) /a, b, c/;

Parameter pm(i) /"a" 1, "b" 2, "c" 3, "d" 4, "e" 5/,
        p1(i),
        p2(i);

* 下面的式子因为pm是参数，所有pm(i)是有值的，因此下面的式子表示当pm(i)不等于0的时候，p1(i)等于1
p1(i) $ (pm(i)) = 1;

* 下面的式子因为j是子集，所以表达的意思遍历子集j中的所有元素
p2(i) $ (j(i)) =
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="逻辑运算符"><a href="#逻辑运算符" class="headerlink" title="逻辑运算符"></a>逻辑运算符</h4><p><code>GAMS</code>中有很多用于计算逻辑表达式的值的运算符，具体来说有有</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221016002853934.png" alt="GAMS中的逻辑运算符-1"></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221016002936753.png" alt="GAMS中的逻辑运算符-2"></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221016003005996.png" alt="GAMS中的逻辑运算符-2的真值表"></p>
<h3 id="4-嵌套条件表达式"><a href="#4-嵌套条件表达式" class="headerlink" title="4. 嵌套条件表达式"></a>4. 嵌套条件表达式</h3><p><code>GAMS</code>中允许使用嵌套表达式，即</p>
<pre class="line-numbers language-gas"><code class="language-gas">term $ (logical_condition1$(logical_condition2$(...)))
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>但是其实嵌套表达式可以使用<code>and</code>语句来连接，两者在本质上是等价的。</p>
<pre class="line-numbers language-gas"><code class="language-gas">term $ (logical_condition1 and logical_condition2 and ...)
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>举一个嵌套条件表达式的例子。假设<code>i</code>是一个静态集合，而<code>k</code>和<code>j</code>都是<code>i</code>的子集，<code>v</code>和<code>u</code>都是参数。那么下面的式子表示让<code>j</code>和<code>v</code>的交集中的元素等于<code>v(i)</code>中对应的值。</p>
<pre class="line-numbers language-gas"><code class="language-gas">u(i) $ (j(i)$k(i)) = v(i) ;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>我们举具体得值为例</p>
<pre class="line-numbers language-gas"><code class="language-gas">Sets i /i1 * i6/,
    j(i) /i1 * i4/,
    k(i) /i3 * i6/;

Parameters v(i) /"i1" -1, "i2" -2, "i3" -3, "i4" -4, "i5" -5, "i6" -6/,
    u(i);

u(i) $ (j(i)$k(i)) = v(i) ;

display u;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>则最终<code>u</code>的值为</p>
<pre class="line-numbers language-gas"><code class="language-gas">u = /"i3" -3, "i4" -4/;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>话说回来，其实嵌套的条件表达式并不推荐使用，最好还是使用<code>and</code>条件运算符。</p>
<p>上面的条件用<code>and</code>条件运算符的版本为</p>
<pre class="line-numbers language-gas"><code class="language-gas">u(i) $ (j(i) and k(i)) = v(i) ;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h3 id="5-条件表达式与赋值语句"><a href="#5-条件表达式与赋值语句" class="headerlink" title="5. 条件表达式与赋值语句"></a>5. 条件表达式与赋值语句</h3><p>事实上，条件表达式的位置不同，赋值的结果也不同。我们上面出现了条件表达式在<code>=</code>左边、在<code>=</code>右边，但是我们其实没有强调在左边和在右边之间的不同。</p>
<p>其实这两者还是存在微妙的不同的，下面我们就将介绍之间的不同。</p>
<h4 id="xxx：条件表达式在左"><a href="#xxx：条件表达式在左" class="headerlink" title="$() = xxx：条件表达式在左"></a>$() = xxx：条件表达式在左</h4><p><strong>条件表达式在<code>=</code>左边表示只有当条件表达式值为真的时候，才会有整个赋值表达式</strong>。</p>
<p>例如下面的例子</p>
<pre class="line-numbers language-gas"><code class="language-gas">rho(i) $ (sig(i) <> 0) = (1./sig(i)) - 1. ;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>假设<code>sig</code>是一个参数，则只有当<code>sig(i)</code>不等于0的时候，才会有<code>rho(i) = (1./sig(I)) -1.</code>这个赋值表达式。</p>
<p>当然，上面说过了只有非0值的逻辑表达式的值为True，所以上面的式子其实可以这样简写</p>
<pre class="line-numbers language-gas"><code class="language-gas">rho(i) $ sig(i)  =  (1./sig(i)) - 1. ;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>于此类似的，所有不等于的某个数<code>x</code>的式子可以这样写</p>
<pre class="line-numbers language-gas"><code class="language-gas">s(i) $ (t(i) - x) = t(i);
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h4 id="xxx-xxx：条件表达式在中间"><a href="#xxx-xxx：条件表达式在中间" class="headerlink" title="xxx $= xxx：条件表达式在中间"></a>xxx $= xxx：条件表达式在中间</h4><p>当条件表达式在中间的时候，形式上有些奇怪，因为没有逻辑表达式。具体形式为</p>
<pre class="line-numbers language-gas"><code class="language-gas">项 $= 项
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>而<strong>条件表达式在中间的含义就是只有当右侧的值不为0的时候，才会有整个赋值表达式</strong>。</p>
<p>例如</p>
<pre class="line-numbers language-gas"><code class="language-gas">Set       i                                         /a,b,c/
Parameter d2(i)  "Data to be used to overwrite d1"  /a 0, b -2 /
          d3(i)  "Empty data parameter";

d3(i) $= d2(i);
* Result: d3('a')=1; d3('b')=-2; d3('c')=1;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="xxx-：条件表达式在右边"><a href="#xxx-：条件表达式在右边" class="headerlink" title="xxx = $()：条件表达式在右边"></a>xxx = $()：条件表达式在右边</h4><p><strong>当条件表达式在<code>=</code>右侧的时候，表示逻辑表达式的值不为0时，条件表达式的值为项的值，否则为0</strong>。</p>
<p>例子就是前面的例子：</p>
<pre class="line-numbers language-gas"><code class="language-gas">A(I) = 1$(ord(I) <= 2) + X(I-2)$(ord(I) > 2);
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h3 id="6-条件表达式与等式（Equation）"><a href="#6-条件表达式与等式（Equation）" class="headerlink" title="6. 条件表达式与等式（Equation）"></a>6. 条件表达式与等式（Equation）</h3><p><code>GAMS</code>中的等式与赋值语句是完全不同的两码事。等式就是首先使用<code>equation</code>声明，而后具体定义的式子。等式中使用的符号和正常的<code>=</code>、<code>&lt;</code>、<code>&gt;</code>不同，就是因为等式是和赋值语句是完全不同的两码事。</p>
<p>上面介绍了赋值语句和条件表达式的细节，下面将介绍等式与条件表达式之间的细节。</p>
<h4 id="条件表达式出现在等式定义中"><a href="#条件表达式出现在等式定义中" class="headerlink" title="条件表达式出现在等式定义中"></a>条件表达式出现在等式定义中</h4><p><strong>当条件表达式出现在等式中，含义其实和条件表达式出现在赋值语句的右侧相同，都是当逻辑表达式的值不为0的时候，存在该项，否则该项为0</strong></p>
<p>注意，在等式中，条件表达式和等式中的等号<code>=e=</code>的位置其实没有关系，不管在那边都是上面的含义。</p>
<p>所以下面的式子</p>
<pre class="line-numbers language-gas"><code class="language-gas">equation eq2;

eq2(i)..      
    sum(j, x(i,j)) $ b =e=  -s(i) $ b;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>表达就是当<code>b = 0</code>时，等式<code>eq2</code>就被定义为<code>0 =e= 0</code></p>
<h4 id="条件表达式出现在等式定义前"><a href="#条件表达式出现在等式定义前" class="headerlink" title="条件表达式出现在等式定义前"></a>条件表达式出现在等式定义前</h4><p><strong>当条件表达式出现在等式定义前，表达的含义是当逻辑表达式的值为0的时候，不会定义该等式，否则定义该等式</strong></p>
<p>所以下面的式子</p>
<pre class="line-numbers language-gas"><code class="language-gas">equation eq1(i);

eq1(i) $ b..  
    sum(j, x(i,j))     =g=  -s(i);
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>表达的就是当<code>b = 0</code>时，不定义等式<code>eq1(i)</code>，所以此时，仅有<code>eq1(i)</code>的声明。如果稍后不定义而直接在模型中使用的话，就会报错。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Jack Wang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://jackwang0107.github.io/2022/10/15/gams-jiao-cheng-3-zi-ji-yu-luo-ji-biao-da-shi/">https://jackwang0107.github.io/2022/10/15/gams-jiao-cheng-3-zi-ji-yu-luo-ji-biao-da-shi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Jack Wang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/GAMS/">
                                    <span class="chip bg-color">GAMS</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/10/16/gams-jiao-cheng-4-xian-xing-mo-xing/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221016165034176.png" class="responsive-img" alt="GAMS教程 4：线性模型">
                        
                        <span class="card-title">GAMS教程 4：线性模型</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文介绍了如何使用GAMS求解线性模型
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-10-16
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/GAMS/" class="post-category">
                                    GAMS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/GAMS/">
                        <span class="chip bg-color">GAMS</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/10/13/gams-jiao-cheng-2-sum-qiu-he-ord-han-shu-yi-ji-tiao-jian-biao-da-shi/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20221015211831052.png" class="responsive-img" alt="GAMS教程 2：GAMS中的运算符与函数">
                        
                        <span class="card-title">GAMS教程 2：GAMS中的运算符与函数</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文介绍了GAMS中的运算符与函数
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-10-13
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/GAMS/" class="post-category">
                                    GAMS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/GAMS/">
                        <span class="chip bg-color">GAMS</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: JackWang&#39;s Blog<br />'
            + '文章作者: Jack Wang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('2'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\\(', '\\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2023</span>
            
            <a href="/about" target="_blank">Jack Wang</a>
            <!-- |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a> -->
            <!-- |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a> -->
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">603.8k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2021";
                        var startMonth = "11";
                        var startDate = "12";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
                <span id="icp"><img src="/medias/icp.png"
                                    style="vertical-align: text-bottom;"/>
                <a href="https://beian.miit.gov.cn" target="_blank">陕ICP备2021014294号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/jackwang0108" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2232123545@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2232123545" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2232123545" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
        
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/libs/others/sakura.js"><\/script>');
            }
        </script>
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
